package com.ddm.service.impl.vxImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ddm.entity.vxEntity.Exam;
import com.ddm.entity.vxEntity.Score;
import com.ddm.entity.vxEntity.User;
import com.ddm.mapper.ExamMapper;
import com.ddm.mapper.ScoreMapper;
import com.ddm.mapper.UserMapper;
import com.ddm.service.vxService.PrizeCalculationService;
import com.ddm.vo.vxVo.PrizeResultVO;
import com.ddm.vo.vxVo.PrizeStatisticsVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Service
@Slf4j
public class PrizeCalculationServiceImpl implements PrizeCalculationService {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private ScoreMapper scoreMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<PrizeResultVO> calculatePrizes(Long examId) {
        // 1. 获取竞赛信息
        Exam exam = examMapper.selectById(examId);
        if (exam == null) {
            throw new RuntimeException("竞赛不存在");
        }

        // 2. 获取所有参与者的成绩，按分数降序排列
        LambdaQueryWrapper<Score> scoreWrapper = new LambdaQueryWrapper<>();
        scoreWrapper.eq(Score::getExamId, examId)
                   .orderByDesc(Score::getTotalScores);
        List<Score> scores = scoreMapper.selectList(scoreWrapper);

        if (scores.isEmpty()) {
            return new ArrayList<>();
        }

        // 3. 计算获奖人数
        int totalParticipants = scores.size();
        int firstPrizeCount = calculatePrizeCount(totalParticipants, exam.getFirstPrizeRatio());
        int secondPrizeCount = calculatePrizeCount(totalParticipants, exam.getSecondPrizeRatio());
        int thirdPrizeCount = calculatePrizeCount(totalParticipants, exam.getThirdPrizeRatio());

        // 4. 构建获奖名单
        List<PrizeResultVO> prizeResults = new ArrayList<>();
        int currentRank = 1;

        // 一等奖
        for (int i = 0; i < firstPrizeCount && i < scores.size(); i++) {
            PrizeResultVO prizeResult = buildPrizeResult(scores.get(i), "一等奖", exam.getFirstPrizeRatio(), currentRank++);
            prizeResults.add(prizeResult);
        }

        // 二等奖
        for (int i = firstPrizeCount; i < firstPrizeCount + secondPrizeCount && i < scores.size(); i++) {
            PrizeResultVO prizeResult = buildPrizeResult(scores.get(i), "二等奖", exam.getSecondPrizeRatio(), currentRank++);
            prizeResults.add(prizeResult);
        }

        // 三等奖
        for (int i = firstPrizeCount + secondPrizeCount; i < firstPrizeCount + secondPrizeCount + thirdPrizeCount && i < scores.size(); i++) {
            PrizeResultVO prizeResult = buildPrizeResult(scores.get(i), "三等奖", exam.getThirdPrizeRatio(), currentRank++);
            prizeResults.add(prizeResult);
        }

        return prizeResults;
    }

    @Override
    public PrizeStatisticsVO getPrizeStatistics(Long examId) {
        // 1. 获取竞赛信息
        Exam exam = examMapper.selectById(examId);
        if (exam == null) {
            throw new RuntimeException("竞赛不存在");
        }

        // 2. 获取参与人数
        LambdaQueryWrapper<Score> scoreWrapper = new LambdaQueryWrapper<>();
        scoreWrapper.eq(Score::getExamId, examId);
        int totalParticipants = scoreMapper.selectCount(scoreWrapper);

        // 3. 计算获奖人数
        int firstPrizeCount = calculatePrizeCount(totalParticipants, exam.getFirstPrizeRatio());
        int secondPrizeCount = calculatePrizeCount(totalParticipants, exam.getSecondPrizeRatio());
        int thirdPrizeCount = calculatePrizeCount(totalParticipants, exam.getThirdPrizeRatio());

        // 4. 构建统计信息
        PrizeStatisticsVO statistics = new PrizeStatisticsVO();
        statistics.setExamId(examId);
        statistics.setExamName(exam.getExamName());
        statistics.setTotalParticipants(totalParticipants);
        statistics.setFirstPrizeCount(firstPrizeCount);
        statistics.setSecondPrizeCount(secondPrizeCount);
        statistics.setThirdPrizeCount(thirdPrizeCount);
        statistics.setFirstPrizeRatio(exam.getFirstPrizeRatio());
        statistics.setSecondPrizeRatio(exam.getSecondPrizeRatio());
        statistics.setThirdPrizeRatio(exam.getThirdPrizeRatio());

        return statistics;
    }

    /**
     * 计算获奖人数
     */
    private int calculatePrizeCount(int totalParticipants, BigDecimal ratio) {
        if (ratio == null || ratio.compareTo(BigDecimal.ZERO) <= 0) {
            return 0;
        }
        BigDecimal count = ratio.multiply(BigDecimal.valueOf(totalParticipants));
        return count.setScale(0, RoundingMode.HALF_UP).intValue();
    }

    /**
     * 构建获奖结果
     */
    private PrizeResultVO buildPrizeResult(Score score, String prizeLevel, BigDecimal prizeRatio, int rank) {
        PrizeResultVO prizeResult = new PrizeResultVO();
        prizeResult.setUserId(score.getUserId());
        prizeResult.setScore(score.getTotalScores());
        prizeResult.setPrizeLevel(prizeLevel);
        prizeResult.setPrizeRatio(prizeRatio);
        prizeResult.setRank(rank);

        // 获取用户信息
        User user = userMapper.selectById(score.getUserId());
        if (user != null) {
            prizeResult.setUserName(user.getUserName());
        } else {
            prizeResult.setUserName("未知用户");
        }

        return prizeResult;
    }
} 